<?php
/**
 * OutsourceBill.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-22
 * Time: 9:19
 */

namespace App\Http\Controllers\Api\Finance;


use App\Exceptions\RunException;
use App\Http\Controllers\Base;
use App\Tables\CashFlow;
use App\Tables\OrderDetail;
use App\Tables\Outsource;
use App\Tables\OutsourcePay;
use App\Tables\OutsourcePayDetail;

class OutsourceBill extends Base
{
    public function getList()
    {
        $id = (int)  $this->request->get('id', 0);
        $firstDate = $this->request->get('firstDate');
        $lastDate = $this->request->get('lastDate');
        $page = (int) $this->request->get('page', 1);
        $pageSize = (int) $this->request->get('pageSize', 30);

        $table = OutsourcePay::query();
        if(!empty($firstDate) and !empty($lastDate)) {
            $table->whereBetween('add_time', [strtotime($firstDate), strtotime($lastDate) + 86400]);
        } else {
            if($id <= 0) {
                $table->whereBetween('add_time', [strtotime(date('Ymd')), strtotime(date('Ymd')) + 86400]);
            }
        }
        if($id > 0) {
            $table->where('oid', $id);
        }
        $table->orderBy('id', 'desc');
        $list = $table->offset(($page -1) * $pageSize)->limit($pageSize)->get();
        $rList  = [];
        $rHeader = ['total' => $list->count(), 'price' => 0, 'period' => 0, 'firstDate' => '', 'lastDate' => ''];
        $fd = $ld = 0;
        foreach ($list as $v) {
            $odList = [];
            foreach($v->details as $vv) {
                $odList[] = [
                    'id' => $vv['id'],
                    'no' => $vv['oid'],
                    'orderDetailId' => $vv['od_id']
                ];
            }
            $rList[] = [
                'id' => $v['id'],
                'addTime' => date('Y-m-d H:i:s', $v['add_time']),
                'outsourceId' => $v['oid'],
                'outsourceName' => $v['o_name'],
                'payMoney' => $v['money'],
                'remark' => $v['remark'],
                'orderDetailList' => $odList
            ];
            if($v['add_time'] > $ld and $ld > 0) {
                $ld = $v['add_time'];
            } else if($ld == 0) {
                $ld = $v['add_time'];
            }

            if($v['add_time'] < $fd and $fd > 0) {
                $fd = $v['add_time'];
            } else if ($fd == 0) {
                $fd = $v['add_time'];
            }

            $rHeader['price'] += (double) $v['money'];
        }
        $rHeader['lastDate'] = date('Y-m-d', $ld);
        $rHeader['firstDate'] = date('Y-m-d', $fd);
        $rHeader['period'] =  $ld - $fd == 0? 0 : ceil(($ld-$fd) / 86400);

        return $this->responseSuccess(['header' => $rHeader, 'list' => $rList]);
    }

    public function add()
    {
        $orderDetailList = (array) $this->request->post('orderDetailList', []);
        $payMoney        = (double) $this->request->post('payMoney', 0);
        $outsourceId     = (int) $this->request->post('outsourceId', 0);
        $remark          = $this->request->post('remark');

        if($payMoney <=0) {
            return $this->responseFail('支付金额不能为0');
        }

        if($outsourceId <= 0) {
            return $this->responseFail('无信息');
        }

        $outsource = Outsource::find($outsourceId);
        if(empty($outsource)) {
            return $this->responseFail('未找到外协商');
        }

        \DB::beginTransaction();
        try {
            $addTime = time();

            $cid = CashFlow::insertGetId([
                'change' => -$payMoney,
                'desc' => "结给外协商:{$outsource['name']} {$payMoney}元",
                'type' => CashFlow::TYPE_Outcome_Outsource,
                'add_time' => $addTime
            ]);
            if($cid <= 0) {
                throw new RunException('增加失败！(1)');
            }
            $opId = OutsourcePay::insertGetId([
                'oid' => $outsource['id'],
                'o_name' => $outsource['name'],
                'money'  => $payMoney,
                'c_id'   => $cid,
                'remark' => $remark,
                'add_time' =>$addTime
            ]);

            if($opId <= 0) {
                throw new RunException('增加失败！(2)');
            }

            $orderDetailList = array_filter($orderDetailList);
            if(!empty($orderDetailList)) {
                $details = OrderDetail::whereIn('id', $orderDetailList)->get();
                if($details->count() != count($orderDetailList)) {
                    return $this->responseFail('增加失败！(2.5)');
                }
                foreach($details as $detail) {
                    $ok = (bool) OutsourcePayDetail::insert([
                        'op_id' => $opId,
                        'oid' => $detail['oid'],
                        'od_id' => $detail['id'],
                        'add_time' => $addTime
                    ]);
                    if(!$ok) { throw new RunException('增加失败！(3)');}
                    $detail['outsource_paid'] = OrderDetail::Outsource_Paid_Ok;
                    if(!(bool) $detail->save()) {
                        throw new RunException('增加失败(4)');
                    }
                }
            }
            \DB::commit();
        }catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        }catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }

    public function update()
    {

    }

    public function del()
    {
        $id = (int) $this->request->post('id', 0);
        if($id <= 0) { return $this->responseFail('无信息');}

        $op = OutsourcePay::find($id);
        if(empty($op)) {
            return $this->responseFail('找不到付款信息');
        }

        \DB::beginTransaction();

        try  {
            $details = $op->details;
            if(!empty($details)) {
                foreach($details as $detail) {
                    $od = $detail->orderDetail;
                    if(empty($od)) {
                        throw new RunException('删除错误！(1)');
                    }
                    $od['outsource_paid'] = OrderDetail::Outsource_Paid_No;
                    if(!(bool) $od->save()) { throw new RunException('删除错误！(2)');}
                    if(!(bool) $detail->delete()){ throw new RunException('删除错误！(3)'); }
                }
            }
            if(!(bool) $op->cashFlow->delete()) { throw new RunException('删除错误！(4)');}
            if(!(bool) $op->delete()) { throw new RunException('删除错误！(5)');}
            \DB::commit();
        }catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        }catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();

    }
}